package common

import (
	"errors"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"math/rand"
	"reflect"
	"strconv"
	"time"
)

//数据验证
func Validate(Model interface{}) string {
	uni := ut.New(zh.New())
	trans, _ := uni.GetTranslator("zh")
	validate := validator.New()
	//注册一个函数，获取struct tag里自定义的label作为字段名
	validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name:=fld.Tag.Get("label")
		return name
	})
	//注册翻译器
	err := zhTranslations.RegisterDefaultTranslations(validate, trans)
	if err!=nil {
		print("翻译器翻译失败")
		return ""
	}

	err = validate.Struct(Model)

	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			return err.Translate(trans)
		}
	}
	return ""
}

//生成随机字符串
func GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

//字符串转整数
func StrChangeUint(Content string) (uint,error) {
	num,err:= strconv.Atoi(Content)
	if err != nil{
		return 0,err
	}
	return uint(num),nil
}

//遍历筛选出两个数组不同的值
func ArrErgodic(arr1 []string ,arr2 []string) ([]string,[]string,error) {
	t := 0
	for a := 0; a < len(arr1)+1; a++ {
		if t != 0 {
			a = 0
			t = 0
		}
		for i := 0; i < len(arr2); i++ {
			if arr1[a] == arr2[i] {
				arr1 = append(arr1[:a],arr1[a + 1:]...)
				arr2 = append(arr2[:i],arr2[i + 1:]...)
				t = 1
			}
		}
	}
	if len(arr1) < 1 && len(arr2) <1  {
		return arr1,arr2,errors.New("两数组值相等")
	}
	return arr1,arr2,nil
}








